import Vue from "vue";
let vueP = Vue.prototype;
/**
 * 选择图片并且鉴黄、鉴别是否真人，最后上传oss并返回对应数组信息
 * @param count 选择照片张数默认1，最大9
 * @param type 表示需要鉴别的类型 all（鉴黄+真人识别）、yellow（鉴黄）、face（人脸）
 * @returns 图片数组，包括每张图片是成功还是失败、错误信息、图片路径
 */
function ieChooseImage(count = 1, type = 'all') {
    return new Promise((resolve, reject) => {
        try {
            count = (count >= 1 && count <= 9 ? count : 1) || 1
            let yType = (type == 'all' || type == 'yellow') || false
            let fType = (type == 'all' || type == 'face') || false
            uni.chooseImage({
                count: count,
                mediaType: ["image"],
                sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
                sourceType: ["camera", "album"], //从相册选择
                success: async function (res) {
                    let urlList = [];
                    vueP.$pv.load("正在上传");
                    for (let i = 0; i < res.tempFiles.length; i++) {
                        let imageOk = false;
                        let avatarOk = false;
                        let tempFilePath = res.tempFiles[i].path;
                        const base64Data = uni.getFileSystemManager().readFileSync(tempFilePath, 'base64')
                        let urlData = {
                            code: 1,
                            msg: '',
                            url: '',
                        }
                        if (fType) {
                            const faceDetectRes = await checkPortrait(base64Data)
                            if (
                                faceDetectRes.data?.result?.face_list[0].face_type.type ==
                                "human" &&
                                faceDetectRes.data?.result?.face_list[0]?.face_type
                                    .probability > 0.5
                            ) {
                                avatarOk = true;
                            } else {
                                urlData.msg = '头像不可以用卡通照片，请重新上传'
                            }
                        }else{
                            avatarOk = true;
                        }
                        if (yType) {
                            const imgCensorRes = await checkPornography(base64Data)
                            if (imgCensorRes.data?.conclusionType == 1) {
                                imageOk = true;
                                
                            } else {
                                urlData.msg = '图像不合规！'
                            }
                        }else{
                            imageOk = true
                        }
                        if (imageOk && avatarOk) {
                            let url = await uploadingList(tempFilePath);
                            if (url) {
                                urlData = {
                                    code: 0,
                                    msg: '成功',
                                    url: url,
                                }

                            } else {
                                urlData = {
                                    code: 1,
                                    msg: '上传图片失败',
                                    url: '',
                                }
                            }
                        }
                       
                        urlList.push(urlData);
                    }
                    vueP.$pv.closeLoad();
                    resolve(urlList)
                },
            });
        } catch (error) {
            this.$pv.msg("图片上传失败");
            console.log(error);
            reject([])
        }
    });

}
// 鉴黄
function checkPornography(base64Str) {
    return new Promise((resolve, reject) => {
        let yellowToken = JSON.parse(uni.getStorageSync('yellowToken'));
        uni.request({
            url: "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined",
            method: "POST",
            data: {
                access_token: yellowToken.Token,
                image: base64Str,
                image_type: 0,
            },
            header: {
                "content-type": "application/x-www-form-urlencoded", // 如果服务器接受的是JSON数据，需要设置content-type为application/json
            },
            success: resolve,
            fail: reject,
        });
    });
}
// 判断是否真人
function checkPortrait(base64Str) {
    return new Promise((resolve, reject) => {
        let faceToken = JSON.parse(uni.getStorageSync('faceToken'));
        uni.request({
            url: "https://aip.baidubce.com/rest/2.0/face/v3/detect",
            method: "POST",
            data: {
                access_token: faceToken.Token,
                image: base64Str,
                image_type: "BASE64",
                face_field: "face_type,gender,expression,age,emotion,mask",
            },
            header: {
                "content-type": "application/x-www-form-urlencoded", // 如果服务器接受的是JSON数据，需要设置content-type为application/json
            },
            success: resolve,
            fail: reject,
        });
    });
}

async function uploadingList(url) {
    console.log(vueP.$upload, "prototype");
    const r = await vueP.$upload(url, (pro) => { });
    return r || false;
}

async function isCheckImage(pathList,type = 'all'){
		let yType = (type == 'all' || type == 'yellow') || false
		let fType = (type == 'all' || type == 'face') || false
		let urlList = [];
		vueP.$pv.load("正在上传");
        console.log(yType,fType,'33333333');
		for (let i = 0; i < pathList.length; i++) {
		    let imageOk = false;
		    let avatarOk = false;
		    let tempFilePath = pathList[i].path;
		    const base64Data = uni.getFileSystemManager().readFileSync(tempFilePath, 'base64')
		    let urlData = {
		        code: 1,
		        msg: '',
		        url: '',
		    }
		    if (fType) {
		        const faceDetectRes = await checkPortrait(base64Data)
                console.log(faceDetectRes,'444444444444');
		        if (
		            faceDetectRes.data?.result?.face_list[0].face_type.type ==
		            "human" &&
		            faceDetectRes.data?.result?.face_list[0]?.face_type
		                .probability > 0.8
		        ) {
		            avatarOk = true;
		        } else {
		            urlData.msg = '头像不可以用卡通照片，请重新上传'
		        }
		    }else{
		        avatarOk = true;
		    }
		    if (yType) {
		        const imgCensorRes = await checkPornography(base64Data)
                console.log(imgCensorRes,'555555');
		        if (imgCensorRes.data?.conclusionType == 1) {
		            imageOk = true;
		            
		        } else {
		            urlData.msg = '图像不合规！'
		        }
		    }else{
		        imageOk = true
		    }
		    if (imageOk && avatarOk) {
		        let url = await uploadingList(tempFilePath);
		        if (url) {
		            urlData = {
		                code: 0,
		                msg: '成功',
		                url: url,
		            }
		
		        } else {
		            urlData = {
		                code: 1,
		                msg: '上传图片失败',
		                url: '',
		            }
		        }
		    }
		   
		    urlList.push(urlData);
		}
		vueP.$pv.closeLoad();
		return urlList
	
}

module.exports = {
    ieChooseImage,
    checkPornography,
    checkPortrait,
	isCheckImage
};
